var fs = require('fs');
var path = require('path');
var request = require('request');
var moment = require('moment');
var tools = require('./tools');
// 新增加的文件
var logsPath = __dirname+'/../logs';
var tempPath = __dirname+'/../temp';
var ip = tools.getHostIP();
var isCoverFloderExist = fs.existsSync(tempPath);
var config = require('../config');
if(!isCoverFloderExist)fs.mkdirSync(tempPath);

fs.watch(logsPath, function (event, filename) {
    var filePath = path.join(logsPath,filename);
    if(event=='rename'&&/\.\d/.test(filename)){
        var randomName = getFileName();
        var newPath= path.join(tempPath,randomName);
        fs.exists(filePath, function (exists) {
            exists&&fs.rename(filePath,newPath,function(){});
        });
    }
});

// 将要传给hdfs的文件
fs.watch(tempPath, function (event, filename) {
    var filePath = path.join(tempPath,filename);
    fs.exists(filePath, function (exists) {
        if(exists){
            postToHDFS(filePath,filename);
        }
    });
});

var postToHDFS = function(file,filename){
    var host = config.hdfsHost;
    var port = config.hdfsPort;
    var day = moment().format('YYYYMMDD');
    var uri = 'http://'+host+':'+port+config.hdfsPath+day+'/'+filename+'?op=CREATE&user.name='+config.hadoopUser+'&namenoderpcaddress='+config.namenoderpcaddress+'&overwrite=true'
    console.info('提交文档：',uri);
    fs.exists(file, function (exists) {
        if(!exists) return;
        fs.createReadStream(file).pipe(request.put(uri,function(error, response, body){
            if(error){
                console.info('error',error);
                return;
            }
            console.info('body',body);
            fs.unlink(file,function(){});
        }))
    });
}

function getFileName(len) {
    len = len || 6;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    var ary = [];
    var time = moment().format('YYYYMMDDHHmmss');
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    ary.push(time);
    ary.push(ip);
    ary.push(pwd);
　　return ary.join('-');
}
